<template>
  <div class="app-container" v-loading="loading">
    <div class="flex flex-wrap">
      <div class="flex justify-between w-full p-b-5">
        <div class="font-black text-xl"><!-- 培训业务分类 --></div>
        <el-row :gutter="10">
          <el-col :span="5">
            <el-date-picker
              style="width: 100%"
              v-model="industryParams.dateArr"
              type="daterange"
              range-separator="-"
              value-format="YYYY-MM-DD"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="getIndustry"
            />
          </el-col>
          <el-col :span="5">
            <el-select
              class="w-full"
              v-model="industryParams.fiscalStatementType"
              placeholder="报表类型"
              @change="getIndustry"
            >
              <el-option
                v-for="item in fiscal_statement_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> </el-select
          ></el-col>
          <el-col :span="5">
            <el-select
              class="w-full"
              v-model="industryParams.isTax"
              placeholder="是否含税"
              @change="getIndustry"
            >
              <el-option
                v-for="item in yes_or_no"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> </el-select
          ></el-col>
          <el-col :span="5">
            <el-select
              v-model="industryParams.hideField"
              placeholder="选择隐藏字段"
              class="w-full"
              multiple
              @change="getData"
            >
              <el-option
                v-for="item in hideOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="3" class="text-right">
            <el-button icon="Download" @click="exportExcel('培训业务分类')"
              >导出</el-button
            >
          </el-col>
        </el-row>
      </div>
      <div class="h-300px w-3/6">
        <EcharsPie :pieObj="pieObj" />
      </div>
      <div class="w-3/6">
        <el-table
          ref="industryTable"
          :data="tableData"
          style="width: 100%"
          border
          stripe
          @row-click="rowClick"
          show-summary
          :sum-text="'统计'"
        >
          <el-table-column prop="businessType" label="名称">
            <template #default="scope">
              <dict-drop
                :options="order_business_type"
                :value="scope.row.businessType"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="!industryParams.hideField.includes('数量')"
            prop="totalPrice"
            label="订单金额(元)"
          />
          <el-table-column
            v-if="!industryParams.hideField.includes('占比')"
            prop="percentage"
            label="新增占比(%)"
          />
          <el-table-column
            type="index"
            label="排名"
            align="center"
            width="60"
          />
        </el-table>
      </div>
    </div>
  </div>
</template>
<script setup name="IndustryTable">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import EcharsPie from './pie'
import EcharsLine from './line'
import { order_business_type } from '@/hooks/dict/order'
import { statisticsIndustry } from '@/api/industryStatistics/index'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
const components = shallowRef({
  EcharsPie,
  EcharsLine
})
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const {
  yes_or_no, //是否
  fiscal_statement_type //是否
} = proxy.useDict('yes_or_no', 'fiscal_statement_type')
const data = reactive({
  industryParams: {
    dateArr: [],
    hideField: []
  },
  pieObj: {},
  tableData: [],

  orderBusinessType: []
})
let { industryParams, pieObj, tableData, orderBusinessType } = toRefs(data)

const hideOptions = [
  {
    label: '占比',
    value: '占比'
  },
  {
    label: '数量',
    value: '数量'
  }
]

watchEffect(
  () => {
    if (order_business_type.value.length > 0) {
      let types = toRaw(order_business_type.value)
      orderBusinessType.value = types.filter(e => e.parentId == '财税-培训产业')
      // console.log('orderBusinessType.value', orderBusinessType.value)
    }
  },
  { flush: 'post' }
)
function goTo(url, data) {
  router.push({ path: url, query: data })
}
// 点击培训业务分类行
function rowClick(row, column, event) {
  let obj = {
    receiptsDates: industryParams.value.dateArr,
    businessType: row.businessType
  }
  // console.log('obj==>', obj)
  goTo('/sales/indent/salesOrder', { salesOrderData: JSON.stringify(obj) })
}

const loading = ref(false)
// 培训业务分类
function getIndustry() {
  loading.value = true
  statisticsIndustry(industryParams.value)
    .then(ref => {
      let pieData = ref.data.map(e => {
        return {
          value: e.percentage,
          name: e.businessType.replace('培训产业-', '')
        }
      })
      pieObj.value.data = pieData
      tableData.value = ref.data
      loading.value = false
    })
    .catch(err => {
      loading.value = false
    })
}
getIndustry()

const showColu = ref(true)
// 前端导出excel
const exportExcel = excelName => {
  let tableBox = {
    expireTable: '服务到期人数分析',
    levelTable: '地市统计分析',
    industryTable: '培训业务分类'
  }
  let tableRef = ''
  for (let key in tableBox) {
    console.log('导出key==>', key)
    if (tableBox[key] === excelName) {
      tableRef = key
    }
  }
  showColu.value = false
  setTimeout(() => {
    try {
      const $e = proxy.$refs[tableRef].$el
      let $table = $e.querySelector('.el-table__fixed')
      if (!$table) {
        $table = $e
      }

      const wb = XLSX.utils.table_to_book($table, { raw: true })
      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      FileSaver.saveAs(
        new Blob([wbout], { type: 'application/octet-stream' }),
        `${excelName}.xlsx`
      )
      showColu.value = true
    } catch (e) {
      showColu.value = true
      if (typeof console !== 'undefined') console.error(e)
    }
  }, 500)
}
</script>
<style lang="scss" scoped>
.el-radio-group.groupBtn :deep(.el-radio__input) {
  display: none;
}
</style>
